package ctgw

import (
	"github.com/beego/beego/v2/core/logs"
	"i-hea/utils/httplib"
)

type msgInfo struct {
	url  string
	data []byte
}

var (
	httpClient *httplib.HttpClient
	msgChan    chan msgInfo
)

const (
	gMsgMaxLen = 10000
)

func SendMessage(url string, message []byte) {

	newData := msgInfo{
		url:  url,
		data: message,
	}

	if len(msgChan) < gMsgMaxLen {
		msgChan <- newData
	}

}

func sendTask(processId int) {

	logs.Info("[%v]消息处理任务启动....", processId)
	for {
		msg := <-msgChan

		receive, err := httpClient.Post(msg.url, msg.data)
		if err != nil {
			logs.Error("[%v]send to host:%v,failed:%v.", processId, msg.url, err)
		} else {
			logs.Debug("[%v]request url:%v,send:%v --> receive:%v.", processId, msg.url, string(msg.data), string(receive))
		}
	}
}

func Init() {

	msgChan = make(chan msgInfo, gMsgMaxLen)
	httpClient = httplib.NewHttpClient()

	for i := 0; i < 5; i++ {
		go sendTask(i)
	}

}
